package org.convallaria.infrastruct.rg.controller;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.convallaria.infrastruct.rg.monitor.RegistryMetrics;
import org.convallaria.infrastruct.rg.service.ServiceDiscoveryManager;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.boot.actuate.endpoint.annotation.Selector;
import org.springframework.boot.actuate.endpoint.web.annotation.WebEndpoint;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 注册发现监控端点
 * 提供详细的监控信息和健康状态
 * 
 * @author gjh
 * @since 2025-01-27
 */
@Slf4j
@Component
@WebEndpoint(id = "registry")
@RequiredArgsConstructor
public class RegistryMonitorController {
    
    private final ServiceDiscoveryManager serviceDiscoveryManager;
    private final RegistryMetrics registryMetrics;
    
    /**
     * 获取注册发现总体状态
     * 
     * @return 总体状态信息
     */
    @ReadOperation
    public Map<String, Object> getRegistryStatus() {
        Map<String, Object> status = new HashMap<>();
        
        // 基础信息
        status.put("totalServices", registryMetrics.getTotalServices());
        status.put("healthyServices", registryMetrics.getHealthyServices());
        status.put("totalInstances", registryMetrics.getTotalInstances());
        status.put("healthyInstances", registryMetrics.getHealthyInstances());
        
        // 健康状态
        boolean isHealthy = registryMetrics.getHealthyServices() > 0;
        status.put("status", isHealthy ? "UP" : "DOWN");
        status.put("healthy", isHealthy);
        
        // 时间戳
        status.put("timestamp", System.currentTimeMillis());
        
        log.debug("获取注册发现状态: {}", status);
        return status;
    }
    
    /**
     * 获取指定服务的监控信息
     * 
     * @param serviceId 服务ID
     * @return 服务监控信息
     */
    @ReadOperation
    public Map<String, Object> getServiceStatus(@Selector String serviceId) {
        Map<String, Object> status = new HashMap<>();
        
        try {
            // 获取服务实例
            List<ServiceInstance> instances = serviceDiscoveryManager.getInstances(serviceId);
            List<ServiceInstance> healthyInstances = serviceDiscoveryManager.getHealthyInstances(serviceId);
            
            // 基础信息
            status.put("serviceId", serviceId);
            status.put("totalInstances", instances.size());
            status.put("healthyInstances", healthyInstances.size());
            status.put("available", !healthyInstances.isEmpty());
            
            // 实例详情
            status.put("instances", instances.stream().map(instance -> {
                Map<String, Object> instanceInfo = new HashMap<>();
                instanceInfo.put("instanceId", instance.getInstanceId());
                instanceInfo.put("host", instance.getHost());
                instanceInfo.put("port", instance.getPort());
                instanceInfo.put("uri", instance.getUri().toString());
                instanceInfo.put("metadata", instance.getMetadata());
                return instanceInfo;
            }).toList());
            
            // 监控指标
            status.put("metrics", Map.of(
                    "instanceCount", registryMetrics.getServiceInstanceCount(serviceId)
            ));
            
            // 健康状态
            status.put("status", !healthyInstances.isEmpty() ? "UP" : "DOWN");
            status.put("healthy", !healthyInstances.isEmpty());
            
        } catch (Exception e) {
            log.error("获取服务状态失败: {}", serviceId, e);
            status.put("serviceId", serviceId);
            status.put("status", "ERROR");
            status.put("healthy", false);
            status.put("error", e.getMessage());
        }
        
        status.put("timestamp", System.currentTimeMillis());
        return status;
    }
    
    /**
     * 获取监控指标
     * 
     * @return 监控指标信息
     */
    @ReadOperation
    public Map<String, Object> getMetrics() {
        Map<String, Object> metrics = new HashMap<>();
        
        // 基础指标
        metrics.put("totalServices", registryMetrics.getTotalServices());
        metrics.put("healthyServices", registryMetrics.getHealthyServices());
        metrics.put("totalInstances", registryMetrics.getTotalInstances());
        metrics.put("healthyInstances", registryMetrics.getHealthyInstances());
        
        // 健康率
        double serviceHealthRate = registryMetrics.getTotalServices() > 0 
                ? (double) registryMetrics.getHealthyServices() / registryMetrics.getTotalServices() 
                : 0.0;
        double instanceHealthRate = registryMetrics.getTotalInstances() > 0 
                ? (double) registryMetrics.getHealthyInstances() / registryMetrics.getTotalInstances() 
                : 0.0;
        
        metrics.put("serviceHealthRate", Math.round(serviceHealthRate * 100.0) / 100.0);
        metrics.put("instanceHealthRate", Math.round(instanceHealthRate * 100.0) / 100.0);
        
        // 时间戳
        metrics.put("timestamp", System.currentTimeMillis());
        
        log.debug("获取监控指标: {}", metrics);
        return metrics;
    }
}
